package com.sdleyou.treepro.common.service.impl;

import com.sdleyou.treepro.common.exception.ServiceException;
import com.sdleyou.treepro.common.rabbitmq.sender.ImmediateSender;
import com.sdleyou.treepro.common.model.dao.UserPetDO;
import com.sdleyou.treepro.common.model.enums.ErrorCodeEnum;
import com.sdleyou.treepro.common.model.vo.CardVO;
import com.sdleyou.treepro.common.model.vo.UserPetVO;
import com.sdleyou.treepro.common.service.CardManager;
import com.sdleyou.treepro.common.service.UserManager;
import com.sdleyou.treepro.common.service.UserPetManager;
import com.sdleyou.treepro.common.service.UserPropManager;
import com.sdleyou.treepro.common.utils.DateUtil;
import com.sdleyou.treepro.common.utils.IdGen;
import com.sdleyou.treepro.common.utils.RedisDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class UserPetManagerImpl implements UserPetManager {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisDelayedQueue redisDelayedQueue;
    @Autowired
    private UserPropManager userPropManager;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private CardManager cardManager;
    @Autowired
    private ImmediateSender immediateSender;
    @Autowired
    private UserManager userManager;

    /**
     * 获取宠物信息
     * @param userId
     * @return
     */
    @Override
    public UserPetVO getPetInfo(String userId) {
        Query query = new Query(Criteria.where("user_id").is(userId));
        UserPetDO userPetDO = mongoTemplate.findOne(query, UserPetDO.class);
        UserPetVO userPetVO = new UserPetVO();
        if(userPetDO!=null) {
            BeanUtils.copyProperties(userPetDO, userPetVO);
            if(2==userPetVO.getPetStatus()){
                UserPetVO.RewardInfo rewardInfo = new UserPetVO.RewardInfo();
                rewardInfo.setRewardType(userPetDO.getRewardType());
                rewardInfo.setImg(userPetDO.getImg());
                rewardInfo.setPropType(userPetDO.getPropType());
                rewardInfo.setPropNum(userPetDO.getPropNum());
                userPetVO.setRewardInfo(rewardInfo);
            }else if(1==userPetVO.getPetStatus()){
                if(userPetVO.getEndTime()-DateUtil.getDateline()<0){
                    userPetVO.setCountDown(0L);
                }else {
                    userPetVO.setCountDown(userPetVO.getEndTime() - DateUtil.getDateline());
                }
            }
            return userPetVO;
        }
        return null;
    }

    /**
     * 宠物寻宝
     * @param userId
     * @return
     */
    @Override
    public Map<String, String> petHunt(String userId) {
        Query query = new Query(Criteria.where("user_id").is(userId));
        UserPetDO userPetDO = mongoTemplate.findOne(query, UserPetDO.class);
        if(userPetDO ==null){
            throw new ServiceException(ErrorCodeEnum.E200.code(), "无宠物信息");
        }
        if(userPetDO.getPetStatus()==1){
            throw new ServiceException(ErrorCodeEnum.E201.code(), "正在寻宝中");
        }
        if(userPetDO.getPetStatus()==2){
            throw new ServiceException(ErrorCodeEnum.E202.code(), "还未领取奖励");
        }
        Update update = new Update();
        update.set("pet_status", 1);
        update.set("start_time", DateUtil.getDateline());
        update.set("end_time", DateUtil.getDateline()+userPetDO.getHuntTime());
        update.set("gmt_modified", DateUtil.getDateline());
        mongoTemplate.updateFirst(query, update, UserPetDO.class);

        //执行延时任务
        immediateSender.send(userPetDO, 1000 * userPetDO.getHuntTime());
//        immediateSender.send(userPetDO, 1000 * 10);

        UserPetDO result = mongoTemplate.findOne(query, UserPetDO.class);
        Map<String, String> map = new HashMap<>();
        map.put("petStatus", result.getPetStatus()+"");
        map.put("huntTime", result.getHuntTime()+"");
        map.put("startTime", result.getStartTime()+"");
        map.put("endTime", result.getEndTime()+"");
        return map;
    }

    /**
     * 给用户添加宠物
     * @param userId
     * @return
     */
    @Override
    public Map<String, String> userAddPet(String userId) {
        Query query = new Query(Criteria.where("user_id").is(userId));
        UserPetDO userPetDO = mongoTemplate.findOne(query, UserPetDO.class);
        if(userPetDO == null){
            userPetDO = new UserPetDO();
            userPetDO.setUserId(userId);
            userPetDO.setPetId(IdGen.uuid());
            userPetDO.setPetStatus(0);
            userPetDO.setStartTime(0L);
            userPetDO.setEndTime(0L);
            userPetDO.setHuntTime(900);
            userPetDO.setGmtCreate(DateUtil.toString(DateUtil.getDateline(), "yyyy-MM-dd HH:mm"));
            userPetDO.setGmtModified(DateUtil.toString(DateUtil.getDateline(), "yyyy-MM-dd HH:mm"));

            mongoTemplate.insert(userPetDO);
            Map<String, String> map = new HashMap<>();
            map.put("pet_id", userPetDO.getPetId());
            return map;
        }else {
            throw new ServiceException(ErrorCodeEnum.E204.code(), "已经有宠物了");
        }
    }

    /**
     * 完成寻宝，更改状态
     * @param userPetDO
     */
    @Override
    public void finishHunt(UserPetDO userPetDO) {
        Query query = new Query(Criteria.where("user_id").is(userPetDO.getUserId()));
        Update update = new Update();
        update.set("pet_status", 2);
        update.set("start_time", 0L);
        update.set("end_time", 0L);
        update.set("gmt_modified", DateUtil.getDateline());

        //增加道具
        // 80%概率获取道具 1-5 随机
        // 20%概率获取明信片 内容为植物知识
        Map<String, String> result = new HashMap<>();
        Random random = new Random();
        int i = random.nextInt(99);

        // 宠物寻宝奖励
        if(i>=0&&i<20){
            //明信片
            update.set("reward_type", "img");
            update.set("img", userManager.getSharePoster(userPetDO.getUserId()));
        }else {
            //随机选取一种
            int num = random.nextInt(5)+1;
            String[] props = {"MANURE", "WATER", "FOOD", "PESTICIDE"};
            String propType = props[random.nextInt(4)];

            update.set("reward_type", "prop");
            update.set("prop_type", propType);
            update.set("prop_num", num+"");
        }

        mongoTemplate.updateFirst(query, update, UserPetDO.class);
    }

    /**
     * 领取奖励接口
     * @param userId
     * @return
     */
    @Override
    public Map<String, String> huntReward(String userId, Integer multiple) {
        UserPetVO petInfo = getPetInfo(userId);
        if(petInfo.getPetStatus() != 2){
            throw new ServiceException(ErrorCodeEnum.E203.code(), "当前状态不能领取");
        }
        Query query = new Query(Criteria.where("user_id").is(userId));
        Update update = new Update();
        update.set("pet_status", 0);
        update.set("start_time", 0L);
        update.set("end_time", 0L);
        update.set("gmt_modified", DateUtil.getDateline());
        //清空奖励
        update.set("reward_type", "");
        update.set("img", "");
        update.set("reward_type", "");
        update.set("prop_type", "");
        update.set("prop_num", "");

        Query q = new Query(Criteria.where("user_id").is(userId));
        UserPetDO userPetDO = mongoTemplate.findOne(q, UserPetDO.class);
        //领取道具奖励
        if (userPetDO != null && "prop".equals(userPetDO.getRewardType())) {
            userPropManager.addProp(userId, userPetDO.getPropType(), userPetDO.getPropNum() * multiple);
        }

        mongoTemplate.updateFirst(query, update, UserPetDO.class);
        return null;
    }

    /**
     * 设置奖励
     */
    private void setReward(String userId){
        //增加道具
        // 80%概率获取道具 1-5 随机
        // 20%概率获取明信片 内容为植物知识
        Map<String, String> result = new HashMap<>();
        Random random = new Random();
        int i = random.nextInt(99);

        // 宠物寻宝奖励
        if(i>=0&&i<20){
            //明信片
            CardVO card = cardManager.random();
            result.put("type", "img");
            result.put("img", card.getImg());
        }else {
            //随机选取一种
            int num = random.nextInt(5)+1;
            String[] props = {"MANURE", "WATER", "FOOD", "PESTICIDE"};
            String propType = props[random.nextInt(4)];
            userPropManager.addProp(userId, propType, num);
            result.put("type", "prop");
            result.put("propType", propType);
            result.put("num", num+"");
        }
    }
}

